'use client';

import { useState, useEffect } from 'react';
import { 
  Search, 
  Send,
  MessageCircle,
  Circle,
} from 'lucide-react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { FadeIn } from '@/components/ui/motion';

interface Message {
  id: number;
  senderId: number | string;
  content: string;
  time: string;
  isTeacher: boolean;
}

interface Parent {
  id: number;
  name: string;
  studentName: string;
  avatar: string;
  lastMessage: string;
  unread: number;
}

// 模拟数据
const mockParents: Parent[] = [
  {
    id: 1,
    name: '张三父亲',
    studentName: '张三',
    avatar: '',
    lastMessage: '老师好，张三今天身体不舒服，请假一天。',
    unread: 2,
  },
  {
    id: 2,
    name: '李四母亲',
    studentName: '李四',
    avatar: '',
    lastMessage: '谢谢老师的关心！',
    unread: 0,
  },
  {
    id: 3,
    name: '王五父亲',
    studentName: '王五',
    avatar: '',
    lastMessage: '好的，我会督促他按时完成作业。',
    unread: 0,
  },
];

// 初始消息数据
const initialMessages: Record<number, Message[]> = {
  1: [ // 张三父亲的消息
    {
      id: 1,
      senderId: 1,
      content: '老师好，张三今天身体不舒服，请假一天。',
      time: '09:30',
      isTeacher: false,
    },
    {
      id: 2,
      senderId: 'teacher',
      content: '好的，注意休息，记得让张三看医生。祝早日康复！',
      time: '09:35',
      isTeacher: true,
    },
    {
      id: 3,
      senderId: 1,
      content: '谢谢老师，已经去看过医生了，开了一些药。',
      time: '09:40',
      isTeacher: false,
    }
  ],
  2: [ // 李四母亲的消息
    {
      id: 1,
      senderId: 2,
      content: '老师，李四最近在学校表现怎么样？',
      time: '昨天 15:20',
      isTeacher: false,
    },
    {
      id: 2,
      senderId: 'teacher',
      content: '李四最近表现不错，作业完成得很认真，课堂上也经常举手发言。',
      time: '昨天 15:30',
      isTeacher: true,
    },
    {
      id: 3,
      senderId: 2,
      content: '谢谢老师的关心！',
      time: '昨天 15:35',
      isTeacher: false,
    }
  ],
  3: [ // 王五父亲的消息
    {
      id: 1,
      senderId: 3,
      content: '老师，王五这次考试成绩怎么样？',
      time: '星期一 14:20',
      isTeacher: false,
    },
    {
      id: 2,
      senderId: 'teacher',
      content: '王五这次进步很大，但还是有些题目需要加强练习。建议多关注应用题部分。',
      time: '星期一 14:30',
      isTeacher: true,
    },
    {
      id: 3,
      senderId: 3,
      content: '好的，我会督促他按时完成作业。',
      time: '星期一 14:35',
      isTeacher: false,
    }
  ]
};

export default function ParentMessagesPage() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedParent, setSelectedParent] = useState<Parent | null>(null);
  const [newMessage, setNewMessage] = useState('');
  const [messages, setMessages] = useState<Record<number, Message[]>>(initialMessages);
  
  // 处理选择家长
  const handleSelectParent = (parent: Parent) => {
    console.log('选择的家长:', parent);
    console.log('当前消息列表状态:', messages);
    
    setSelectedParent(parent);
    // 确保消息存在
    if (!messages[parent.id]) {
      console.log('该家长没有消息记录，创建空数组');
      setMessages(prev => ({
        ...prev,
        [parent.id]: []
      }));
    }
  };
  
  // 过滤家长列表
  const filteredParents = mockParents.filter(parent => 
    parent.name.toLowerCase().includes(searchTerm.toLowerCase()) || 
    parent.studentName.toLowerCase().includes(searchTerm.toLowerCase())
  );
  
  // 获取当前选中家长的消息记录
  const currentMessages = selectedParent ? (messages[selectedParent.id] || []) : [];
  console.log('当前显示的消息:', currentMessages);
  
  // 发送消息
  const handleSendMessage = () => {
    if (!newMessage.trim() || !selectedParent) return;
    
    console.log('准备发送消息:', {
      parentId: selectedParent.id,
      content: newMessage,
      currentMessages: messages[selectedParent.id]
    });
    
    // 创建新消息
    const newMessageObj: Message = {
      id: Date.now(),
      senderId: 'teacher',
      content: newMessage,
      time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
      isTeacher: true,
    };
    
    // 更新消息状态
    setMessages(prevMessages => {
      const updatedMessages = {
        ...prevMessages,
        [selectedParent.id]: [...(prevMessages[selectedParent.id] || []), newMessageObj]
      };
      console.log('更新后的消息状态:', updatedMessages);
      return updatedMessages;
    });
    
    setNewMessage('');
  };

  // 监听消息变化
  useEffect(() => {
    console.log('messages状态更新:', messages);
  }, [messages]);

  // 监听选中家长变化
  useEffect(() => {
    console.log('选中的家长更新:', selectedParent);
    if (selectedParent) {
      console.log('该家长的消息记录:', messages[selectedParent.id]);
    }
  }, [selectedParent, messages]);

  return (
    <div className="h-screen w-full p-4 bg-gray-50">
      <div className="h-full max-w-6xl mx-auto bg-white rounded-lg shadow-lg overflow-hidden">
        <div className="flex h-full">
          {/* 左侧联系人列表 */}
          <div className="w-80 flex flex-col border-r border-gray-200">
            {/* 搜索框 */}
            <div className="p-4 border-b border-gray-200">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                <Input
                  type="search"
                  placeholder="搜索家长或学生..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-9 w-full bg-gray-50"
                />
              </div>
            </div>

            {/* 联系人列表 */}
            <div className="flex-1 overflow-y-auto">
              {filteredParents.map((parent) => (
                <div
                  key={parent.id}
                  onClick={() => handleSelectParent(parent)}
                  className={`
                    flex items-center gap-3 p-4 cursor-pointer
                    hover:bg-gray-50 transition-colors
                    ${selectedParent?.id === parent.id ? 'bg-blue-50' : ''}
                  `}
                >
                  <Avatar className="h-12 w-12 border-2 border-white shadow-sm">
                    <AvatarFallback className="bg-blue-100 text-blue-600">
                      {parent.name[0]}
                    </AvatarFallback>
                  </Avatar>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between">
                      <span className="font-medium text-gray-900">{parent.name}</span>
                      {parent.unread > 0 && (
                        <span className="inline-flex items-center justify-center w-5 h-5 text-xs font-medium text-white bg-blue-500 rounded-full">
                          {parent.unread}
                        </span>
                      )}
                    </div>
                    <p className="text-sm text-blue-600">学生：{parent.studentName}</p>
                    <p className="text-sm text-gray-500 truncate">{parent.lastMessage}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 右侧聊天区域 */}
          <div className="flex-1 flex flex-col">
            {selectedParent ? (
              <>
                {/* 聊天头部 */}
                <div className="flex items-center gap-3 p-4 border-b border-gray-200 bg-white">
                  <Avatar className="h-12 w-12 border-2 border-white shadow-sm">
                    <AvatarFallback className="bg-blue-100 text-blue-600">
                      {selectedParent.name[0]}
                    </AvatarFallback>
                  </Avatar>
                  <div>
                    <h2 className="font-medium text-gray-900">{selectedParent.name}</h2>
                    <p className="text-sm text-blue-600">学生：{selectedParent.studentName}</p>
                  </div>
                </div>

                {/* 消息列表 */}
                <div className="flex-1 overflow-y-auto p-4 space-y-4">
                  {currentMessages.map((message) => (
                    <div
                      key={message.id}
                      className={`flex ${message.isTeacher ? 'justify-end' : 'justify-start'}`}
                    >
                      <div className={`flex items-end gap-2 max-w-[80%] ${
                        message.isTeacher ? 'flex-row-reverse' : ''
                      }`}>
                        <Avatar className="h-8 w-8 flex-shrink-0">
                          <AvatarFallback className={
                            message.isTeacher ? 'bg-blue-100 text-blue-600' : 'bg-gray-100 text-gray-600'
                          }>
                            {message.isTeacher ? 'T' : selectedParent.name[0]}
                          </AvatarFallback>
                        </Avatar>
                        <div>
                          <div className={`rounded-2xl px-4 py-2 ${
                            message.isTeacher
                              ? 'bg-blue-500 text-white'
                              : 'bg-gray-100 text-gray-900'
                          }`}>
                            <p className="text-sm">{message.content}</p>
                          </div>
                          <p className={`text-xs text-gray-500 mt-1 ${
                            message.isTeacher ? 'text-right' : ''
                          }`}>
                            {message.time}
                          </p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>

                {/* 输入框 */}
                <div className="p-4 border-t border-gray-200 bg-white">
                  <div className="flex gap-2">
                    <Input
                      placeholder="输入消息..."
                      value={newMessage}
                      onChange={(e) => setNewMessage(e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter' && !e.shiftKey) {
                          e.preventDefault();
                          handleSendMessage();
                        }
                      }}
                      className="flex-1"
                    />
                    <Button
                      onClick={handleSendMessage}
                      className="bg-blue-500 hover:bg-blue-600 text-white"
                    >
                      <Send className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </>
            ) : (
              <div className="flex-1 flex items-center justify-center bg-gray-50">
                <div className="text-center">
                  <div className="w-16 h-16 rounded-full bg-blue-50 flex items-center justify-center mx-auto mb-4">
                    <MessageCircle className="h-8 w-8 text-blue-500" />
                  </div>
                  <p className="text-gray-600 font-medium">选择一个家长开始聊天</p>
                  <p className="text-sm text-gray-500 mt-1">在左侧列表选择要联系的家长</p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
} 